package com.okyai.cms.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.okyai.cms.domain.CmsApp;
import com.okyai.cms.domain.CmsCategory;
import com.okyai.cms.generate.bean.AttributeBean;
import com.okyai.cms.generate.bean.PageBean;
import com.okyai.cms.generate.utils.BasicUtil;
import com.okyai.cms.generate.utils.ParserUtil;
import com.okyai.cms.service.ICmsCategoryService;
import com.okyai.cms.service.ICmsContentService;
import com.okyai.common.core.controller.BaseController;
import com.okyai.common.core.domain.AjaxResult;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.FileUtil;


/**
 * 生成器
 * @author 13424
 *
 */
@Controller
@RequestMapping("/cms/generate")
public class GeneraterController extends BaseController {

	/*
	 * log4j日志记录
	 */
	protected final Logger LOG = LoggerFactory.getLogger(this.getClass());

	/**
	 * 文章管理业务层
	 */
	@Autowired
    private ICmsContentService cmsContentService;

	/**
	 * 栏目管理业务层
	 */
	@Autowired
    private ICmsCategoryService cmsCategoryService;


	/**
	 * 更新主页
	 *
	 * @return
	 */
	@RequestMapping()
	public String index(HttpServletRequest request, ModelMap model) {
		return "/cms/generate/index";
	}

	/**
	 * 生成主页
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping("/generateIndex")
	@RequiresPermissions("cms:generate:index")
	@ResponseBody
	public AjaxResult generateIndex(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 模版文件名称
		String tmpFileName = "index.html";
		// 生成后的文件名称
		String generateFileName = "index";

        ParserUtil.generate(tmpFileName, generateFileName);
        return AjaxResult.success();
		
	}



	/**
	 * 生成列表的静态页面
	 *
	 * @param request
	 * @param response
	 * @param CategoryId
	 */
	/*
	@RequestMapping("/{CategoryId}/genernateColumn")
	@RequiresPermissions("cms:generate:column")
	@ResponseBody
	public AjaxResult genernateColumn(HttpServletRequest request, HttpServletResponse response, @PathVariable Long CategoryId) throws IOException {
		// 获取站点id
		CmsApp app = BasicUtil.getApp();
		List<CmsCategory> columns = new ArrayList<CmsCategory>();
		// 如果栏目id小于0则更新所有的栏目，否则只更新选中的栏目
		if (CategoryId>0) {
			CmsCategory categoryEntity = new CmsCategory();
			categoryEntity.setId(CategoryId);
			categoryEntity.setAppId(app.getAppId());
			columns = categoryBiz.queryChilds(categoryEntity);
		} else {
			// 获取所有的内容管理栏目
            CategoryEntity categoryEntity=new CategoryEntity();
            categoryEntity.setAppId(app.getAppId());
			columns = categoryBiz.query(categoryEntity);
		}
		List<CategoryBean> articleIdList = null;
			// 1、设置模板文件夹路径
			// 获取栏目列表模版
			for (CategoryEntity column : columns) {
				ContentBean contentBean = new ContentBean();
				contentBean.setContentCategoryId(column.getId());
				// 分类是列表
				if(column.getCategoryType().equals("1")) {
					// 判断模板文件是否存在
					if (!FileUtil.exist(ParserUtil.buildTempletPath(column.getCategoryListUrl()))) {
						LOG.error("模板不存在：{}", column.getCategoryUrl());
						continue;
					}
					//获取模板中列表标签中的条件
					Map<String, Object> map = new HashMap<>();
					map.put(ParserUtil.APP_ID, BasicUtil.getAppId());
					PageBean page = new PageBean();
					map.put(ParserUtil.HTML, ParserUtil.HTML);
					map.put(ParserUtil.URL, BasicUtil.getUrl());
					map.put(ParserUtil.PAGE, page);
					AttributeBean attributeBean = new AttributeBean();
					// 获取文章列表模板标签属性
					ParserUtil.read(column.getCategoryListUrl(), map, page, attributeBean);
					contentBean.setFlag(attributeBean.getFlag());
					contentBean.setNoflag(attributeBean.getNoflag());
					contentBean.setOrder(attributeBean.getOrder());
					contentBean.setOrderBy(attributeBean.getOrderby());
				}
				articleIdList = contentBiz.queryIdsByCategoryIdForParser(contentBean);
				// 判断列表类型
				switch (column.getCategoryType()) {
					//TODO 暂时先用字符串代替
				case "1": // 列表
					ParserUtil.generateList(column, articleIdList.size());
					break;
				case "2":// 单页
					if(articleIdList.size()==0){
						CategoryBean columnArticleIdBean=new CategoryBean();
						CopyOptions copyOptions=CopyOptions.create();
						copyOptions.setIgnoreError(true);
						BeanUtil.copyProperties(column,columnArticleIdBean,copyOptions);
						articleIdList.add(columnArticleIdBean);
					}
					ParserUtil.generateBasic(articleIdList);
					break;
				}
			}

        return AjaxResult.success();
	}
*/
	/**
	 * 根据栏目id更新所有的文章
	 *
	 * @param request
	 * @param response
	 * @param columnId
	 */
	/*
	@RequestMapping("/{columnId}/generateArticle")
	@RequiresPermissions("cms:generate:article")
	@ResponseBody
	public AjaxResult generateArticle(HttpServletRequest request, HttpServletResponse response, @PathVariable String columnId) throws IOException {
		String dateTime = request.getParameter("dateTime");
		// 网站风格物理路径
		List<CategoryBean> articleIdList = null;
		List<CategoryEntity> categoryList = null;
		AttributeBean attributeBean = new AttributeBean();
		ContentBean contentBean = new ContentBean();
		contentBean.setBeginTime(dateTime);
		Map<String, Object> map = new HashMap<>();
		map.put(ParserUtil.APP_ID, BasicUtil.getAppId());
		PageBean page = new PageBean();
		map.put(ParserUtil.HTML, ParserUtil.HTML);
		map.put(ParserUtil.URL, BasicUtil.getUrl());
		map.put(ParserUtil.PAGE, page);
		if(Integer.parseInt(columnId) == 0){
			CategoryEntity categoryEntity = new CategoryEntity();
			categoryList = categoryBiz.query(categoryEntity);
			for(CategoryEntity category : categoryList){
				contentBean.setContentCategoryId(category.getId());
				// 分类是列表
				if(category.getCategoryType().equals("1")){
					// 判断模板文件是否存在
					if (!FileUtil.exist(ParserUtil.buildTempletPath(category.getCategoryListUrl())) || StringUtils.isEmpty(category.getCategoryListUrl())) {
						LOG.error("模板不存在：{}",category.getCategoryUrl());
						continue;
					}
					// 获取文章列表表属性
					ParserUtil.read(category.getCategoryListUrl(),map, page,attributeBean);
					contentBean.setFlag(attributeBean.getFlag());
					contentBean.setNoflag(attributeBean.getNoflag());
					contentBean.setOrder(attributeBean.getOrder());
					contentBean.setOrderBy(attributeBean.getOrderby());
				}
				articleIdList = contentBiz.queryIdsByCategoryIdForParser(contentBean);
				// 有符合条件的就更新
				if (articleIdList.size() > 0) {
					CmsParserUtil.generateBasic(articleIdList);
				}
			}
		}else {
			CategoryEntity category = (CategoryEntity) categoryBiz.getEntity(Integer.parseInt(columnId));
			contentBean.setContentCategoryId(columnId);
			// 分类是列表
			if(category.getCategoryType().equals("1")){
				// 获取文章列表表属性
				// 判断模板文件是否存在
				if (!FileUtil.exist(ParserUtil.buildTempletPath(category.getCategoryUrl()))) {
					LOG.error("模板不存在：{}",category.getCategoryUrl());
                    return AjaxResult.error("模板不存在");
				}
				ParserUtil.read(category.getCategoryListUrl(),map, page,attributeBean);
				contentBean.setFlag(attributeBean.getFlag());
				contentBean.setNoflag(attributeBean.getNoflag());
				contentBean.setOrder(attributeBean.getOrder());
				contentBean.setOrderBy(attributeBean.getOrderby());
			}
			articleIdList = contentBiz.queryIdsByCategoryIdForParser(contentBean);
			// 有符合条件的就更新
			if (articleIdList.size() > 0) {
				ParserUtil.generateBasic(articleIdList);
			}
		}
        return AjaxResult.success();
	}

*/

	/**
	 * 用户预览主页
	 *
	 * @param request
	 * @return
	 */
	/*
	@RequestMapping("/{position}/viewIndex")
	public String viewIndex(HttpServletRequest request, @PathVariable String position, HttpServletResponse response) {
		String indexPosition = app.getAppHostUrl() + File.separator + ParserUtil.HTML + File.separator + app.getAppId()
				+ File.separator + position + ParserUtil.HTML_SUFFIX;
		return "redirect:" + indexPosition;
	}
	*/
}
